'''
Created on Oct 11, 2012

@author: daeheehan
'''
from pprint import pprint
from github3 import login, GitHub
from getpass import getpass, getuser

import datetime
import dateutil.parser
import time
import sys

# Github User information
GITHUB_USER_ID = "booknara"
GITHUB_USER_ID_1 = "booknaratest"
GITHUB_USER_ID_2 = "jangho87"
GITHUB_USER_ID_3 = 'luispigu'
GITHUB_USER_ID_4 = 'skswhwo'

GITHUB_USER_PW = "qwer1234"
GITHUB_USER_PW_1 = "wasd1234"

if __name__ == '__main__':
    pass

gh = login(GITHUB_USER_ID_2, password=GITHUB_USER_PW)
print gh.ratelimit_remaining, 'request remaining'

# Github Repository information
GITHUB_USER_NAME = 'h5bp'
GITHUB_REPOSITORY_NAME = 'html5-boilerplate'

# Contributors information file
WATCH_CONTRIBUTORS_FILE = 'html5_boilerplate_contributors_watch.txt'

# Contributors Watch time information file
CONTRIBUTORS_WATCH_TIME_FILE = 'html5_boilerplate_contributors_watch_time.txt'

watch_contributors = []
contributors_watch_time_dict = {}

try:
    # Github Bootstrap project contributors list from files
    f_collaborators = open(WATCH_CONTRIBUTORS_FILE, 'r')
    
    for line in f_collaborators:
        if not line.strip():
            continue
        # We got something, save it
        else:
            tuple_list = line.split(',')
            
            login = tuple_list[0].strip()
            b_watch = tuple_list[1].strip()
            if b_watch == '1':
                watch_contributors.append(login)

    f_collaborators.close()

    print 'loading watch_contributors file is finished'
    
    for w_contributor in watch_contributors:
        print 'login id: ' +  w_contributor
        user = gh.user(w_contributor)
#        user = gh.user('coltrane')

        try:
            for event in user.iter_events(number = -1):
                if (event.type == 'WatchEvent') and (event.repo[0] == GITHUB_USER_NAME) and (event.repo[1] == GITHUB_REPOSITORY_NAME):
                    print w_contributor, event.type, event.created_at, event.repo[0], event.repo[1]
                    contributors_watch_time_dict[w_contributor] = event.created_at
#                    pprint(vars(event))
                    break
    
                if(gh.ratelimit_remaining < 100):
                    time.sleep(60 * 60)
                    
        except Exception as e:
            print 'The inner Exception', e.args[0]
            continue
#        break

    f_contributors_watch_time = open(CONTRIBUTORS_WATCH_TIME_FILE, 'w')
    print 'Printing dictionary: watch'
    for key, value in contributors_watch_time_dict.items():
        sys.stdout.write(key + ", " + str(value) + '\n')
        f_contributors_watch_time.write(key + ", " + str(value) + '\n')

    f_contributors_watch_time.close()

except Exception as e: 
    print 'The final Exception' + str(e.args[0])

#    pprint(vars(sub))
print str(gh.ratelimit_remaining) + ' request remaining'

print
print 'Finally the end'